package impl

import (
	"context"
	"github.com/starmotioncf/common/region"
	"github.com/starmotioncf/soutchatinternal/model"
	"github.com/starmotioncf/soutchatinternal/repository"
	"gorm.io/gorm"
)

type countryRepository struct {
	*repository.Repository
}

func NewCountryRepository(r *repository.Repository) repository.CountryRepository {
	return &countryRepository{
		Repository: r,
	}
}

func (r *countryRepository) Get(ctx context.Context, code string) (m *model.Country, err error) {
	if code == "" {
		return nil, gorm.ErrRecordNotFound
	}
	err = r.ReadDB(ctx).Where("code = ?", code).First(&m).Error
	return
}

func (r *countryRepository) GetByRegion(ctx context.Context, rgn region.Region) (m []*model.Country, err error) {
	if rgn == 0 {
		return nil, nil
	}
	err = r.ReadDB(ctx).Where("region = ? and status = 1", rgn).
		Order("hot desc").
		Order("sort asc").Find(&m).Error
	return
}

func (r *countryRepository) GetByArea(ctx context.Context, area int) (m *model.Country, err error) {
	if area == 0 {
		return nil, gorm.ErrRecordNotFound
	}
	err = r.ReadDB(ctx).Where("area = ?", area).First(&m).Error
	return
}

func (r *countryRepository) GetAll(ctx context.Context) (m []*model.Country, err error) {
	err = r.ReadDB(ctx).Where("status =1").Order("hot desc").Order("sort asc").Find(&m).Error
	return
}
